import React, { Component } from 'react';
import * as echarts from 'echarts/core';
import {
    BarChart,
    // 系列类型的定义后缀都为 SeriesOption
    BarSeriesOption,
    LineChart,
    LineSeriesOption,
} from 'echarts/charts';
import {
    TitleComponent,
    // 组件类型的定义后缀都为 ComponentOption
    TitleComponentOption,
    GridComponent,
    GridComponentOption,
    // 数据集组件
    DatasetComponent,
    DatasetComponentOption,
    // 内置数据转换器组件 (filter, sort)
    TransformComponent,
    TooltipComponent,
} from 'echarts/components';
import { LabelLayout, UniversalTransition } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';

// 通过 ComposeOption 来组合出一个只有必须组件和图表的 Option 类型
type ECOption = echarts.ComposeOption<
    BarSeriesOption | LineSeriesOption | TitleComponentOption | GridComponentOption | DatasetComponentOption
>;

// 注册必须的组件
echarts.use([
    TitleComponent,
    TooltipComponent,
    GridComponent,
    DatasetComponent,
    TransformComponent,
    BarChart,
    LabelLayout,
    UniversalTransition,
    CanvasRenderer,
]);

const option: ECOption = {
    title: {
        text: 'ECharts 入门示例',
    },
    tooltip: {},
    xAxis: {
        data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子'],
    },
    yAxis: {},
    series: [
        {
            name: '销量',
            type: 'bar',
            data: [5, 20, 36, 10, 10, 20],
        },
    ],
};

class ECharts extends Component<any> {
    constructor(props: any) {
        super(props);
    }
    shouldComponentUpdate(_nextProps: any, _nextState: any) {
        console.log('shouldComponentUpdate');
        console.log(_nextState);
        console.log(_nextProps);
        return false;
        // return true;
    }
    componentDidMount() {
        // 基于准备好的dom，初始化echarts实例
        let chartDiv = document.getElementById('echart-div') || document.createElement('div');
        let myChart = echarts.init(chartDiv);
        // 绘制图表
        myChart.setOption(option);
        console.log('componentDidMount');
    }
    componentDidUpdate(_prevProps: any, _prevState: any, _snapshot: any) {
        console.log('componentDidUpdate');
        console.log(_prevProps);
        console.log(_prevState);
    }
    render() {
        let { children } = this.props;
        console.log('render');
        console.log(children);
        return (
            <div>
                <div id="echart-div" style={{ width: 400, height: 400 }}></div>
                {children}
            </div>
        );
    }
}

export default ECharts;
